//
//  CLWorkViewController.m
//  JG
//
//  Created by 程龙 on 2023/10/24.
//

#import "CLWorkViewController.h"
#import <WebKit/WebKit.h>
#import "CLButton.h"
#import "CLScanViewController.h"
#import "CLScanView.h"
@interface CLWorkViewController ()<WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate>{
    WKWebViewConfiguration *config;
    WKWebView *wView;
}
@property (nonatomic, strong) UIBarButtonItem *homeItem;
@property (nonatomic, strong) UIBarButtonItem *exitItem;
@property (nonatomic, strong) UIButton *logoutBtn;
@property (nonatomic, strong) UIView *maskView;

@end

@implementation CLWorkViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.gk_navTitle = @"";
    self.gk_navRightBarButtonItems = @[self.exitItem, self.homeItem];
    
    
    config = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *controller = [[WKUserContentController alloc] init];
    
    NSString * string1 = @"OpenScan";
    [controller addScriptMessageHandler:self name:string1];
    
    NSString * string2 = @"nativeCallback";
    [controller addScriptMessageHandler:self name:string2];
    
    
    NSString * string3 = @"ibaAuthMptSetup";
    [controller addScriptMessageHandler:self name:string3];
    
    config.userContentController = controller;
    
    config.applicationNameForUserAgent = @"HT_IBA_CP_AUTH";
    
    wView = [[WKWebView alloc] initWithFrame:CGRectMake(0, CL_SizeStatusBarAndNavigationBarHeight, CLWIDTH, CLHEIGHT-CL_SizeStatusBarAndNavigationBarHeight) configuration:config];
    wView.UIDelegate = self;
    wView.navigationDelegate = self;
    wView.allowsBackForwardNavigationGestures = YES;
    //    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.address]];
    //
    //    [wView loadRequest:request];
    [self.view addSubview:wView];
    
    //    [wView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    //    [wView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:NULL];
    
    CLLog(@"请求地址：%@",self.address);
    
    
    [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
        request.path=url_token;
        request.methodType=ZBMethodTypePOST;
    }  success:^(id responseObject,ZBURLRequest * request){
        if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
            [CLData sharedClass].token = responseObject[@"data"][@"token"];
            
            [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
                request.path=url_update;
                request.methodType=ZBMethodTypePOST;
                request.parameters = @{@"currentVersion":[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"],
                                       @"device":@"iOS",
                                       @"model":[[UIDevice currentDevice] model],
                                       @"workCode":@"",
                                       
                };
            }  success:^(id responseObject,ZBURLRequest * request){
                if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"200"]) {
                    if([CLTool isNullToDictionary:responseObject[@"data"]] == YES){
                        CLLog(@"没有新版本");
                        return;
                    }
                    if([[NSString stringWithFormat:@"%@",responseObject[@"data"][@"isForce"]] isEqualToString:@"1"] ){
                        Dialog()
                        //出现动画
                            .wShowAnimationSet(AninatonZoomIn)
                        //消失动画
                            .wHideAnimationSet(AninatonZoomOut)
                        
                            .wEventOKFinishSet(^(id anyID, id otherData) {
                                NSString * _dataString = [[NSString alloc] initWithData:[responseObject[@"data"][@"downloadurl"] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES] encoding:NSASCIIStringEncoding];
                                
                                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_dataString] options:nil completionHandler:^(BOOL success) {
                                    
                                }];
                            })
                            .wTitleSet(@"发现新版本，建议立即更新")
                            .wMessageSet(responseObject[@"data"][@"features"])
                            .wOKTitleSet(@"更新")
                            .wMessageColorSet(DialogColor(0x333333))
                            .wTitleColorSet(DialogColor(0x666666))
                            .wOKColorSet([UIColor orangeColor])
                        
                            .wTitleFontSet(15)
                            .wShadowShowSet(YES)
                            .wShadowCanTapSet(NO)
                            .wAutoCloseSet(NO)
                            .wTagSet(999)
                            .wTypeSet(DialogTypeNornal).wStartView(self.view);
                    }else{
                        Dialog()
                        //出现动画
                            .wShowAnimationSet(AninatonZoomIn)
                        //消失动画
                            .wHideAnimationSet(AninatonZoomOut)
                            .wEventCancelFinishSet(^(id anyID, id otherData) {
                                [self maskViewAction];
                            })
                            .wEventOKFinishSet(^(id anyID, id otherData) {
                                NSString * _dataString = [[NSString alloc] initWithData:[responseObject[@"data"][@"downloadurl"] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES] encoding:NSASCIIStringEncoding];
                                
                                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_dataString] options:nil completionHandler:^(BOOL success) {
                                    
                                }];
                            })
                            .wTitleSet(@"发现新版本，建议立即更新")
                            .wMessageSet(responseObject[@"data"][@"features"])
                            .wOKTitleSet(@"更新")
                            .wCancelTitleSet(@"取消")
                            .wMessageColorSet(DialogColor(0x333333))
                            .wTitleColorSet(DialogColor(0x666666))
                            .wOKColorSet([UIColor orangeColor])
                            .wCancelColorSet([UIColor blueColor])
                            .wTitleFontSet(15)
                            .wTypeSet(DialogTypeNornal).wStartView(self.view);
                    }
                    
                    
                }else{
                    [CLTool cl_showFail:responseObject[@"msg"] block:^{
                        
                    }];
                }
                
                
            } failure:^(NSError * _Nullable error) {
                [CLTool cl_showFail:@"请求错误" block:^{
                    
                }];
            } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
                NSLog(@"请求完成");
            }];
            
        }else{
            [CLTool cl_showFail:responseObject[@"msg"] block:^{
                
            }];
        }
        
        
    } failure:^(NSError * _Nullable error) {
        [CLTool cl_showFail:@"请求错误" block:^{
            
        }];
        
    } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
        NSLog(@"请求完成");
    }];
    


    

    
    
    
    if([CLTool cl_getUser:@"workToken"].length != 0){
        [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
            request.url=url_stgt;
            request.headers = nil;
            request.methodType=ZBMethodTypePOST;
            request.parameters = @{@"ticketType":@"MPT",@"ticketValue":[CLTool cl_getUser:@"workToken"]};
        }  success:^(id responseObject,ZBURLRequest * request){
            if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"0"]) {
                
                
               
                
                NSString *str = [NSString stringWithFormat:@"%@?stgt=%@&redirectUrl=%@%@",url_home,responseObject[@"data"][@"ticket"][@"value"],url_h5,@"/"];
                
                NSLog(@"===%@",str);
                
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str]];
                
                [self->wView loadRequest:request];
                //     [self.view addSubview:self->wView];
                
                
                
            }else{
                [CLTool cl_showFail:responseObject[@"msg"] block:^{
                    [self.navigationController popViewControllerAnimated:YES];

                }];
            }
            
            
        } failure:^(NSError * _Nullable error) {
            [CLTool cl_showFail:@"请求错误" block:^{
                [self.navigationController popViewControllerAnimated:YES];

            }];
            
        } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
            NSLog(@"请求完成");
        }];
    }else{
        
//        [self.homeItem setHidden:YES];
//        [self.exitItem setHidden:YES];
        
        self.gk_navRightBarButtonItems = nil;
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.address]];
        
        [wView loadRequest:request];
    }
    
    
    
    
    
    self.maskView = [[UIView alloc]init];
    self.maskView.frame = CGRectMake(0, 0, CLWIDTH, CLHEIGHT);
    self.maskView.backgroundColor = [UIColor blackColor];
    self.maskView.alpha = 0.3;
    self.maskView.userInteractionEnabled = YES;
    UITapGestureRecognizer * ges = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(maskViewAction)];
    [self.maskView addGestureRecognizer:ges];
    [self.view addSubview:self.maskView];
    
    
    self.logoutBtn = [UIButton new];
    self.logoutBtn.frame = CGRectMake(CLWIDTH-100*CLSCALE, CL_SizeStatusBarAndNavigationBarHeight, 90*CLSCALE, 30*CLSCALE);
    [self.logoutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [self.logoutBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.logoutBtn.titleLabel.font = CLFONT(10);
    self.logoutBtn.backgroundColor = [UIColor whiteColor];
    [self.logoutBtn jk_cornerRadius:5*CLSIZE strokeSize:0 color:[UIColor blackColor]];
    [self.logoutBtn addTarget:self action:@selector(logoutAction) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:self.logoutBtn];
    
    
    [self.maskView setHidden:YES];
    [self.logoutBtn setHidden:YES];
    
    

}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    
}
- (void)viewWillAppear:(BOOL)animated{
    
}
//#pragma mark - KVO
//- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
//    if ([keyPath isEqualToString:@"title"]) {
//        self.gk_navTitle = wView.title;
//    }else if ([keyPath isEqualToString:@"canGoBack"]) {
//        if ([wView canGoBack]) {
//            self.gk_interactivePopDisabled = YES;
//        }else {
//            self.gk_interactivePopDisabled = NO;
//        }
//    }
//}
// 重写下面的方法，拦截点击返回
- (BOOL)navigationShouldPopOnClick {
    [self maskViewAction];
    // do something
    if (wView.canGoBack) {
       [wView goBack];

    }else{
        if([CLTool cl_getUser:@"workToken"].length == 0){
            [self.navigationController popViewControllerAnimated:YES];

        }
    }
    
    return NO;
}
// 重写下面的方法，拦截手势返回
- (BOOL)navigationShouldPopOnGesture {
    [self maskViewAction];
    // do something
//    if (wView.canGoBack) {
//        [wView goBack];
//        
//    }else{
//        
//    }
    return NO;
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    NSLog(@"-----%@",message.name);
    NSLog(@"-----%@",message.body);
    
    
    NSString * string1 = @"OpenScan";
    if ([message.name isEqualToString:string1]) {
        CLScanViewController *vc = [[CLScanViewController alloc]init];
        vc.block = ^(NSString * _Nonnull _str) {
            NSLog(@"=======%@",_str);
            [self->wView evaluateJavaScript: [NSString stringWithFormat:@"CloseScan('%@')",_str]
                       completionHandler:^(id response, NSError * error) {
                    NSLog(@"response: %@, \nerror: %@", response, error);
             }];
        };
        [self.navigationController pushViewController:vc animated:YES];

    }

    
    NSString * string3 = @"ibaAuthMptSetup";
    if ([message.name isEqualToString:string3]) {
    
//        [self.homeItem setHidden:NO];
//        [self.exitItem setHidden:NO];
        
        self.gk_navRightBarButtonItems = @[self.exitItem, self.homeItem];
        
        if([NSString stringWithFormat:@"%@",message.body].length != 0){
            [CLTool cl_saveUser:@"1" key:@"loginType"];
            [CLTool cl_saveUser:message.body key:@"workToken"];
        }


        
    }
    
    
//    [CLTool cl_showSuccess:[NSString stringWithFormat:@"js调用ios成功 %@",message.name] block:^{
//
//    }];
    
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        
        if ([challenge previousFailureCount] == 0) {
            
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
            
        } else {
            
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
            
        }
        
    } else {
        
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        
    }
}
/* 在收到响应后，决定是否跳转 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    
    
    CLLog(@"跳转的地址%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
- (UIBarButtonItem *)homeItem {
    if (!_homeItem) {
        CLButton *btn = [CLButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 44, 44);
        [btn setImage:[UIImage imageNamed:@"首页"] forState:UIControlStateNormal];
        [btn addTarget:self action: @selector(homeAction) forControlEvents: UIControlEventTouchDown];
        btn.imageRect = CGRectMake(10, 10, 24, 24);
        
        _homeItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    return _homeItem;
}

- (UIBarButtonItem *)exitItem {
    if (!_exitItem) {
        CLButton *btn = [CLButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 44, 44);
        [btn setImage:[UIImage imageNamed:@"更多"] forState:UIControlStateNormal];
        [btn addTarget:self action: @selector(exitAction) forControlEvents: UIControlEventTouchDown];
        btn.imageRect = CGRectMake(10, 10, 24, 24);
        
        _exitItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    }
    return _exitItem;
}
- (void)homeAction{

    if([CLTool cl_getUser:@"workToken"].length != 0){
        [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
            request.url=url_stgt;
            request.headers = nil;
            request.methodType=ZBMethodTypePOST;
            request.parameters = @{@"ticketType":@"MPT",@"ticketValue":[CLTool cl_getUser:@"workToken"]};
        }  success:^(id responseObject,ZBURLRequest * request){
            if ([[NSString stringWithFormat:@"%@",responseObject[@"code"]] isEqualToString:@"0"]) {
                

                
                
                NSString *str = [NSString stringWithFormat:@"%@?stgt=%@&redirectUrl=%@%@",url_home,responseObject[@"data"][@"ticket"][@"value"],url_h5,@"/"];

                NSLog(@"===%@",str);
                
                NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:str]];
                
                [self->wView loadRequest:request];
                //     [self.view addSubview:self->wView];
                
                
                
            }else{
                [CLTool cl_showFail:responseObject[@"msg"] block:^{
                    [self.navigationController popViewControllerAnimated:YES];

                }];
            }
            
            
        } failure:^(NSError * _Nullable error) {
            [CLTool cl_showFail:@"请求错误" block:^{
                [self.navigationController popViewControllerAnimated:YES];

            }];
            
        } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
            NSLog(@"请求完成");
        }];
    }else{

    }

    
    
}
- (void)exitAction{
    if([self.logoutBtn isHidden] == YES){
        [self.maskView setHidden:NO];
        [self.logoutBtn setHidden:NO];
    }else{
        [self.maskView setHidden:YES];
        [self.logoutBtn setHidden:YES];
    }
    
    
}
- (void)logoutAction{
    
    Dialog()
    //出现动画
        .wShowAnimationSet(AninatonZoomIn)
    //消失动画
        .wHideAnimationSet(AninatonZoomOut)
        .wEventCancelFinishSet(^(id anyID, id otherData) {
            [self maskViewAction];
        })
        .wEventOKFinishSet(^(id anyID, id otherData) {
            
            [ZBRequestManager requestWithConfig:^(ZBURLRequest *request){
                request.url=url_wokr_logout;
                request.methodType=ZBMethodTypeGET;
                request.userInfo = @{@"type":@"888"};

            }  success:^(id responseObject,ZBURLRequest * request){
                
                [CLTool cl_saveUser:@"" key:@"loginType"];
                [CLTool cl_saveUser:@"" key:@"workToken"];
                
                
                WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];
                  [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes]
                           completionHandler:^(NSArray<WKWebsiteDataRecord *> * __nonnull records) {
                             for (WKWebsiteDataRecord *record in records)
                             {
                //               if ( [record.displayName containsString:@"baidu"]) //取消备注，可以针对某域名清除，否则是全清
                //               {
                                 [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes
                                                      forDataRecords:@[record]
                                                    completionHandler:^{
                                                      NSLog(@"Cookies for %@ deleted successfully",record.displayName);
                                                    }];
                //               }
                             }
                           }];

                [self.navigationController popViewControllerAnimated:YES];

            } failure:^(NSError * _Nullable error) {
                [CLTool cl_showFail:@"请求错误" block:^{
                    
                }];
            } finished:^(id responseObject, NSError *error, ZBURLRequest *request) {
                NSLog(@"请求完成");
            }];
            

            
            
        })
        .wTitleSet(@"温馨提示")
        .wMessageSet(@"是否确认退出登录")
        .wOKTitleSet(@"确认")
        .wCancelTitleSet(@"取消")
        .wMessageColorSet(DialogColor(0x333333))
        .wTitleColorSet(DialogColor(0x666666))
        .wOKColorSet([UIColor orangeColor])
        .wCancelColorSet([UIColor blueColor])
        .wTitleFontSet(15)
        .wTypeSet(DialogTypeNornal).wStart();
}

- (void)maskViewAction{
    [self.maskView setHidden:YES];
    [self.logoutBtn setHidden:YES];
}
//开始加载

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    NSLog(@"开始加载网页===%@",webView.URL);
    
    [CLTool cl_showLoading];
    
}
//加载完成

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    NSLog(@"加载完成===%@",webView.URL);
    
    [CLTool cl_closeWithshowView];
    
}
//加载失败

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    NSLog(@"加载失败===%@",webView.URL);
    
    [CLTool cl_showFail:@"加载失败" block:^{
        
    }];
    
}
#pragma mark -  Alert弹窗
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message ? : @"" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }];
    [alertController addAction:action];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark -  Confirm弹框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message ? : @"" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }];
    
    UIAlertAction * confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }];
    
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark -  TextInput弹框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler {
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    UIAlertAction * action = [UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text ? : @"");
    }];
    [alertController addAction:action];
    
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    NSLog(@"webViewWebContentProcessDidTerminate");
    
    config.applicationNameForUserAgent = @"HT_IBA_CP_AUTH";
    [self homeAction];
    
    
  //  exit(0);
}
@end
